<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Sate;
use App\Model\Goodstype;
use Illuminate\Support\Facades\Redis;
use App\Model\Goods;
use App\Model\AdminLoopModel;
use App\Model\Goodsattr;
use App\Model\Goodspic;

/**
 * 前台首页相关API
 * @author [wt1ao] <[42435645@qq.com]>
 */
class IndexApi extends Controller
{
    //
    /**
     * [getSate 获取站点信息]
     * @return [array] [先查redis 如果redis没有就查询数据库,并写进redis]
     */
    public static function getSate()
    {
        $sateHashKey = 'Shop_Sate_data_hash';

        $sates = Redis::hGetAll($sateHashKey);

        if (empty($sates)) {

            $sates = Sate::select('name', 'desc','message', 'record', 'phone', 'icon', 'logo')->first()->toArray();

            Redis::hMSet($sateHashKey, $sates);

        }

    	return $sates;
    }

    /**
     * [getTypes 查询获取redis获取商品父级分类信息]
     * @return [array] [返回所有商品父级分类信息]
     */
    public function getTypes()
    {
        $setKey = 'goods_types_set_data';

        if (empty(Redis::sMembers($setKey))) {

            $res = $this->setTypesRedis();

        }

        $hashKey = Redis::sMembers($setKey);

        // dd($hashKey);

        foreach($hashKey as $v) {

            $types[] = Redis::hGetAll($v);

        }

        return $types;
    }


    /**
     * [getSonsTypes 查询获取redis获取商品子级分类信息]
     * @param  Request $request [description]
     * @return [object]           [返回请求过来的id相应的子级分类信息]
     */
    public function getSonsTypes(Request $request)
    {

        $setSonsKey = 'goods_types_set_data_sons:'.$request->id;

        $hashKey = Redis::sMembers($setSonsKey);

        foreach ($hashKey as $v)
        {

            $types[] = Redis::hGetAll($v);

        }

        return response()->json($types);

    }

    /**
     * [getAllTypes 查询Redis获取所有分类信息]
     *@return [array] [返回一个数组]
     */
    public function getAllTypes()
    {
      $setKey = 'goods_types_set_data';

      if (empty(Redis::sMembers($setKey))) {

            $res = $this->setTypesRedis();

      }

      $hashKey = Redis::sMembers($setKey);

      foreach ($hashKey as $key => $value) {

            $types[] = Redis::hGetAll($value);

      }

      foreach($types as $k => $v) {

        $hashSonsKey = Redis::sMembers('goods_types_set_data_sons:'.$v['id']);

        foreach($hashSonsKey as $i) {

           $types[$k]['sons'][] = Redis::hGetAll($i);

         }

      }

      return $types;

    }

    /**
     * [getMysqlTypes 查询数据库获取分类信息]
     * @return [array] [description]
     */
    public function getMysqlTypes()
    {

    	$types = Goodstype::select('id', 'type_name')->where('pid', '0')->orderBy('id', 'desc')->get()->toArray();

        foreach($types as $k => $v) {

            $types[$k]['sons'] = Goodstype::select('id', 'type_name')->orderBy('id', 'desc')->where('pid', $v['id'])->get()->toArray();

        }

        return $types;
    }


    /**
     * [setTypesRedis 从数据库中查询所有分类信息写进Redis中]
     */
    public function setTypesRedis()
    {

        $setKey = 'goods_types_set_data';
        $setSonsKey = 'goods_types_set_data_sons';
        $hashKey = 'goods_types_hash_data';

        $types = $this->getMysqlTypes();

        foreach($types as $type) {

            //判断是否有子级分类
            if (!empty($type['sons'])) {

                foreach($type['sons'] as $sons) {

                    Redis::sAdd($setSonsKey.':'.$type['id'], $hashKey.':'.$sons['id']);

                    Redis::hMSet($hashKey.':'.$sons['id'], $sons);

               }
            }

            unset($type['sons']);

            Redis::sAdd($setKey, $hashKey.':'.$type['id']);

            Redis::hMSet($hashKey.':'.$type['id'], $type);

        }

    }

    /**
     * [getManTypes 获取父级分类的子分类]
     * @param  [string] $name [要获取的父级分类名]
     * @return [array]       [返回一个二维数组]
     */
    public function getManTypes($name)
    {

        $Id = Goodstype::select('id')->where('type_name', $name)->first()->toArray();


        $types = $this->getReidsTypes($Id['id']);

        return $types;

    }

    /**
     * [getReidsTypes 获取Reids里的子分类信息]
     * @param  [int] $id [要获取的父级分类ID]
     * @return [array]     [返回一个二维数组]
     */
    public function getReidsTypes($id)
    {

        $setKey = 'goods_types_set_data_sons:'.$id;

        $hashKey = Redis::sMembers($setKey);

        foreach($hashKey as $v) {

            $types[] = Redis::hGetAll($v);

        }


        return $types;


    }

    /**
     * [getTypeGoods 获取分类下商品]
     * @param  [int] $id [分类id]
     * @return [array]     [返回一个包含商品信息的二维数组]
     */
    public function getTypeGoods($id)
    {

    	$setKey = 'types_with_goods_set_data:'.$id;

    	$hashKey = 'types_with_goods_hash_data:';

    	if(empty(Redis::sMembers($setKey))) {

    		$goods = Goods::select('id', 'goods_name', 'goods_pic', 'price')
	    			->where([['type_id', $id], ['buy_num', '>', 100]])
	    			->get()
	    			->toArray();

	    	foreach($goods as $v) {

	    		Redis::sAdd($setKey, $hashKey.$v['id']);

	    		Redis::hMSet($hashKey.$v['id'], $v);

	    	}

    	}

    	$goodsHash = Redis::sRandMember($setKey, 6);

    	foreach( $goodsHash as $v ) {

    		$goods[] = Redis::hGetAll($v);

    	}

    	return $goods;

    }

    /**
     * [jsGetTypeGoods 使用ajax获取分类下商品]
     * @param  Request $request [在ajax传过来id]
     * @return [array]           [返回一个二维数组]
     */
    public function jsGetTypeGoods(Request $request)
    {

        $setKey = 'types_with_goods_set_data:'.$request->id;

        $hashKey = 'types_with_goods_hash_data:';

        if(empty(Redis::sMembers($setKey))) {

            $goods = Goods::select('id', 'goods_name', 'goods_pic', 'price')
                    ->where([['type_id', $request->id], ['buy_num', '>', 100]])
                    ->get()
                    ->toArray();

            foreach($goods as $v) {

                Redis::sAdd($setKey, $hashKey.$v['id']);

                Redis::hMSet($hashKey.$v['id'], $v);

            }

        }

        $goodsHash = Redis::sRandMember($setKey, 6);

        foreach( $goodsHash as $v ) {

            $goods[] = Redis::hGetAll($v);

        }

        return $goods;

    }

    /**
     * [getHotGoods 从redis中获取热销商品数据]
     * @return [array]
     */
    public function getHotGoods(Request $request)
    {
        $hotGoodsSet = 'hot_goods_set';
        $hotGoodsHash = 'hot_goods_hash_id:';

        //判断redis中是否有热销商品，如果没有就查询数据库
        if (empty(Redis::sMembers($hotGoodsSet))) {

            $this->hotMysqlGoods();

        }

        //随机从集合里拿出固定的数量的元素
        $GoodsHashArr = Redis::sRandMember($hotGoodsSet, $request->num);

        foreach ($GoodsHashArr as $k => $v) {

            $hotGoods[] = Redis::hGetAll($v);


        }

        return $hotGoods;


    }

    public function getLoopPics()
    {
        $setKey = 'shop_looppics_set_data';

        $hashKey = 'shop_looppics_hash_data:';

        if(empty(Redis::sMembers($setKey))) {

            $loops = AdminLoopModel::select('id','goods_id', 'loop_pic')
                                    ->where('status', 1)
                                    ->get()
                                    ->toArray();

            foreach($loops as $v) {

                Redis::sAdd($setKey, $hashKey.$v['id']);

                Redis::hMSet($hashKey.$v['id'], $v);
            }
        }

        $hashArr = Redis::sMembers($setKey);

        foreach( $hashArr as $i) {

          $loops[] = Redis::hGetAll($i);
        }

        return $loops;
    }

    /**
     * 去数据库查询热销商品并插入redis的方法
     *@return 没有返回值
     */
    public function hotMysqlGoods()
    {
      $hotGoodsSet = 'hot_goods_set';
      $hotGoodsHash = 'hot_goods_hash_id:';
      //判断redis中是否有热销商品，如果没有就查询数据库
      $goods = Goods::select('id', 'goods_pic', 'goods_name', 'price', 'buy_num')
                      ->where([
                      ['status', '0'],
                      ['buy_num', '>', 100],
                      ])
                      ->get()
                      ->toArray();

      foreach($goods as $v) {

          Redis::sAdd($hotGoodsSet, $hotGoodsHash.$v['id']);

          Redis::hMSet($hotGoodsHash.$v['id'], $v);

          $color = Goodsattr::select('color')->where('goods_id', $v['id'])->get()->toArray();
          $size = Goodsattr::select('size')->where('goods_id', $v['id'])->get()->toArray();
          $pic = Goodspic::select('pic')->where('goods_id', $v['id'])->get()->toArray();

          $setColorKey = 'goods_set_color_data:'.$v['id'];
          $setSizeKey = 'goods_set_size_data:'.$v['id'];
          $setPicKey = 'goods_set_pic_data:'.$v['id'];

          foreach($color as $c) {
            Redis::sAdd($setColorKey, $c['color']);
          }
          foreach($size as $s) {
            Redis::sAdd($setSizeKey, $s['size']);
          }
          foreach($pic as $p) {
            Redis::sAdd($setPicKey, $p['pic']);
          }
      }
    }

}
